package com.gogant.spider.util;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;

import com.gogant.spider.http.HttpResponse;

public class FileUtils {
    private static boolean createDirectory(File file) {
        if (file.exists() && file.isDirectory()) {
            return true;
        } else {
            return file.mkdirs();
        }
    }

    public static boolean saveToPath(HttpResponse resp, File base) {
        URL url = resp.getURL();
        String directory = url.getProtocol() + "/" + url.getHost();
        if (url.getPort() > 0) {
            directory += "-" + url.getPort();
        }
        String path = url.getPath();
        String fileName;
        if (path == null || path.length() == 0) {
            fileName = "index.html";
        } else if (path.endsWith("/")) {
            directory += path;
            fileName = "index.html";
        } else {
            int idx = path.lastIndexOf('/');
            if (idx >= 0) {
                directory += path.substring(0, idx + 1);
                fileName = path.substring(idx + 1);
            } else {
                fileName = path;
            }
        }
        if (url.getQuery() != null) {
            String query = url.getQuery().replaceAll("[&=]", "-");
            int idx = fileName.lastIndexOf('.');
            if (idx > 0) {
                fileName = fileName.substring(0, idx) + "-" + query + fileName.substring(idx);
            } else if (idx == 0) {
                fileName = query + fileName;
            } else {
                fileName = fileName + "-" + query;
            }
        }
        if (!directory.endsWith("/")) {
            directory += "/";
        }
        File file = new File(base, directory + fileName);
        return saveToFile(resp, file);
    }

    public static boolean saveToFile(HttpResponse resp, File file) {
        if (!createDirectory(file.getParentFile())) {
            return false;
        }
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(file);
            output.write(resp.getContentBytes());
            output.flush();
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (Exception e) {
                }
            }
        }
    }
}
